package com.black.service.controller;

import com.alibaba.fastjson2.JSONObject;
import com.black.protocol.ErrorCode;
import com.black.protocol.Response;
import com.black.service.entity.ResourceEntity;
import com.black.service.service.ResourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@Slf4j
@RestController
@RequestMapping("/service/resource")
public class ResourceController {

    @Resource
    private ResourceService resourceService;

    /**
     * export function uploadFile(data: any, param: string) {
     * return request({
     * 'url': host + 'file' + param || '',
     * 'method': 'post',
     * 'headers': { 'Content-Type': 'multipart/form-data' },
     * data,
     * });
     * }
     * <p>
     * function customUpload(params: any) {
     * const file = params.file;
     * const formData = new FormData();
     * formData.append('file', file);
     * uploadFile(formData, '?type=png&userFlag=user').then((res: any) => {
     * searchOptions.resourceId = res.id;
     * searchOptions.resourceUrl = res.url.replace(/^http:\/\/.+?\//, API_URL);
     * });
     * }
     *
     * @param file    文件
     * @param request 请求
     * @return 保存结果
     */
    @PostMapping("/file")
    @ResponseBody
    public Response<?> saveFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return Response.fail(ErrorCode.ERROR_PARAM_MISSING);
        }
        String resourceType = request.getParameter("type");
        if (resourceType.isEmpty()) {
            return Response.fail(ErrorCode.ERROR_PARAM_MISSING);
        }
        String fileName = file.getOriginalFilename();
        try {
            ResourceEntity resourceEntity = new ResourceEntity();
            resourceEntity.setResourceType(resourceType);
            resourceEntity.setResourceName(fileName);
            resourceEntity.setResourceData(file.getBytes());
            return resourceService.saveFile(resourceEntity);
        } catch (Exception e) {
            log.error("resource file save failed:", e);

            return Response.fail(ErrorCode.ERROR_UNKNOWN);
        }
    }

    @GetMapping("/file")
    public Response<?> testDownload(HttpServletResponse response, HttpServletRequest request) {
        String resourceId = request.getParameter("id");
        if (resourceId == null || resourceId.isEmpty()) {
            return Response.fail(ErrorCode.ERROR_PARAM_MISSING);
        }
        byte[] fileData = resourceService.loadFile(resourceId);
        if (fileData == null || fileData.length == 0) {
            return Response.fail(ErrorCode.ERROR_FILE_NOT_EXIST);
        }
        //String fileName = "upload.jpg";
        //response.setHeader("content-type", "application/octet-stream");
        //response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + resourceId);
        try {
            OutputStream os = response.getOutputStream();
            os.write(fileData, 0, fileData.length);
            os.flush();
        } catch (IOException e) {
            log.error("write resource data to stream failed", e);
            return Response.fail(ErrorCode.ERROR_UNKNOWN);
        }
        return null;
    }

    @PostMapping("/file_url")
    @ResponseBody
    public Response<?> getResourceUrl(@RequestBody JSONObject params) {
        String resourceId = params.getString("resourceId");
        return Response.success(resourceService.getUrlByResourceId(resourceId));
    }

    @PostMapping("/qr_code_gen")
    @ResponseBody
    public Response<?> generateQrCode(@RequestBody JSONObject params) {
        return resourceService.generateQrCode(params);
    }
}
